package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.pojo.Video;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VideoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class VideosService {

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 上传小视频
     *
     * @param picFile   小视频封页
     * @param videoFile 小视频
     * @return
     */
    public String saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        User user = UserThreadLocal.get();
        Video video = new Video();
        video.setUserId(user.getId());
        video.setSeeType(1);
        try {
            PicUploadResult uploadResult = picUploadService.upload(picFile);
            String picPathName = uploadResult.getName();
            video.setPicUrl(picPathName);
            //上传视频
            StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(),
                    videoFile.getSize(),
                    StringUtils.substringAfter(videoFile.getOriginalFilename(), "."),
                    null);
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + "/" + storePath.getFullPath());

            return this.videoApi.saveVideo(video);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取视频列表信息
     *
     * @param page     页码
     * @param pageSize 页尺寸
     * @return
     */
    public PageResult queryVideoList(Integer page, Integer pageSize) {
        /*
         从redis中获取推荐视频。如果redis未命中，则从mongodb中获取。
         */
        //1.获取当前用户
        page = 1; //TODO app的问题
        User user = UserThreadLocal.get();
        //2.组建分页数据
        PageResult pageResult = new PageResult();
        //2.1处理基本信息
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setPages(0);
        pageResult.setCounts(0);

        PageInfo<Video> pageInfo = null;
        // 从redis获取推荐视频的vid
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + user.getId();
        String vidsValue = this.redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isNotEmpty(vidsValue)) {
            // 对命中的数据进行分割，得到id的集合
            String[] vids = vidsValue.split(",");
            // 开始索引计算公式：（当前页-1）*每页显示的大小
            int startIndex = (page - 1) * pageSize;
            if (startIndex < vids.length) {
                int endIndex = startIndex + pageSize - 1;
                if (endIndex >= vids.length) {
                    endIndex = vids.length - 1;
                }

                // 封装分页所需的vid
                List<Long> vidList = new ArrayList<>();
                for (int i = startIndex; i <= endIndex; i++) {
                    vidList.add(Long.valueOf(vids[i]));
                }
                // 获取推荐视频列表
                List<Video> videoList =  videoApi.queryVideoListByVids(vidList);
                pageInfo = new PageInfo<>();
                pageInfo.setRecords(videoList);
            }
        }
        //2.2分页获取"视频列表"
        if (pageInfo == null){
            pageInfo = videoApi.queryVideoList(page, pageSize);
        }
        //2.3获取"视频列表"
        List<Video> records = pageInfo.getRecords();
        //2.4定义集合,存储"视频详细信息"
        List<VideoVo> videoVoList = new ArrayList<>();
        //2.5定义集合,存储视频所关联的"用户信息"
        List<Long> userIds = new ArrayList<>();
        //2.6遍历"视频列表"
        for (Video record : records) {
            //2.6.1封装视频详细信息
            VideoVo videoVo = new VideoVo();
            videoVo.setUserId(record.getUserId());
            videoVo.setCover(record.getPicUrl());
            videoVo.setVideoUrl(record.getVideoUrl());
            videoVo.setId(record.getId().toHexString());
            videoVo.setSignature("我就是我~");

            //获取评论数
            Long commentCount = quanZiApi.queryCommentCount(videoVo.getId(), 2);
            videoVo.setCommentCount(commentCount == null ? 0 : commentCount.intValue());
            //判断是否关注
            String followUserKey = "VIDEO_FOLLOW_USER_" + user.getId() + "_" + videoVo.getUserId();
            videoVo.setHasFocus(redisTemplate.hasKey(followUserKey) ? 1 : 0);
            //判断是否点赞（1是，0否）
            String userKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + videoVo.getId();
            videoVo.setHasLiked(redisTemplate.hasKey(userKey) ? 1 : 0);
            //获取点赞数
            String key = "QUANZI_COMMENT_LIKE_" + videoVo.getId();
            String value = redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotEmpty(value)) {
                videoVo.setLikeCount(Integer.valueOf(value));
            } else {
                videoVo.setLikeCount(0);
            }

            //获取视频用户id,把id存储到集合中,用来获取用户详细信息.
            //所以,集合中不需要添加重复的用户id
            if (!userIds.contains(record.getUserId())) {
                userIds.add(record.getUserId());
            }

            //把视频详细信息封装到集合中
            videoVoList.add(videoVo);
        }

        //3.封装所有的用户信息
        //3.1根据用户id集合,查询所有用户信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = userInfoService.queryList(queryWrapper);
        //3.2遍历所有的"视频详细信息集合",给每个对象添加"用户信息"
        for (VideoVo videoVo : videoVoList) {
            for (UserInfo userInfo : userInfos) {
                if (videoVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    videoVo.setNickname(userInfo.getNickName());    //昵称
                    videoVo.setAvatar(userInfo.getLogo());          //头像
                    break;
                }
            }
        }
        //4.把"视频详细信息集合",封装到分页数据中
        pageResult.setItems(videoVoList);
        return pageResult;
    }

    // 关注用户
    public boolean userFocus(Integer userId) {
        User user = UserThreadLocal.get();
        Boolean result = videoApi.followUser(user.getId(), userId.longValue());
        if (result) {
            String redisKey = "VIDEO_FOLLOWER_USER" + user.getId() + "_" + userId;
            redisTemplate.opsForValue().set(redisKey, "1");
            return true;
        }
        return false;
    }


    public boolean userUnFocus(Integer userId) {
        User user = UserThreadLocal.get();
        Boolean result = videoApi.disFollowUser(user.getId(), userId.longValue());
        if (result) {
            String redisKey = "VIDEO_FOLLOWER_USER" + user.getId() + "_" + userId;
            redisTemplate.delete(redisKey);
            return true;
        }
        return false;
    }
}
